package com.seeyon.apps.ebs.rcyh.manager.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.ebs.rc.dao.RcDao;
import com.seeyon.apps.ebs.rc.manager.RcManager;
import com.seeyon.apps.ebs.rc.manager.impl.RcManagerImpl;
import com.seeyon.apps.ebs.rc.utils.RcUtils;
import com.seeyon.apps.ebs.rcyh.dao.RcyhDao;
import com.seeyon.apps.ebs.rcyh.manager.RcyhManager;
import com.seeyon.apps.ebs.rcyh.objenum.DqType;
import com.seeyon.apps.ebs.rcyh.po.EbsRcMxPo;
import com.seeyon.apps.ebs.rcyh.po.EbsRcPo;
import com.seeyon.apps.ebs.rcyh.utils.RcyhUtils;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.template.manager.TemplateManager;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.JDBCAgent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class RcthManagerImpl implements RcyhManager {
    private static Log log = LogFactory.getLog(RcthManagerImpl.class);
    private static ColManager colManager = (ColManager) AppContext.getBean("colManager");
    private static FormApi4Cap4 cap4FormManager = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
    private static EnumManager enumManager = (EnumManager) AppContext.getBean("enumManagerNew");
    private static OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
    private static TemplateManager templateManager = (TemplateManager) AppContext.getBean("templateManager");
    private static RcyhDao rcyhDao = (RcyhDao) AppContext.getBean("rcyhDao");
    private static RcDao rcDao = (RcDao) AppContext.getBean("ebsRcDao");
    private static RcManager rcManager = (RcManager) AppContext.getBean("ebsRcManager");
    private static SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static String scheduleArchiveCode = AppContext.getSystemProperty("ebsRc.scheduleArchiveCode");
    private static String deptWeihuCode = AppContext.getSystemProperty("ebsRc.deptWeihuCode");
    private Map<String,String> typeMap = new HashMap<String,String>(){
        {
            put("1","Jan");
            put("2","Feb");
            put("3","Mar");
            put("4","Apr");
            put("5","May");
            put("6","Jun");
            put("7","Jul");
            put("8","Aug");
            put("9","Sep");
            put("10","Oct");
            put("11","Nov");
            put("12","Dec");
        }
    };


    @Override
    public JSONObject updateRcMiddleTable(JSONObject param) {
        JSONObject result = new JSONObject();
        JDBCAgent jdbcAgent = null;
        try {
            Integer dataYear = param.getInteger("year");
            jdbcAgent = RcManagerImpl.getJdbcAgent();
            LocalDate now = LocalDate.now();
            List<Integer> yearsBetween = RcyhUtils.getYearsBetween(dataYear, now.getYear(), true);
            yearsBetween = new ArrayList<>();
            yearsBetween.add(dataYear);
            //查询所有动迁部门信息
            List<Map<String, Object>> departments = rcDao.getAllNeedDept();
            if (departments!=null||!departments.isEmpty()){
                for (Map<String, Object> department : departments) {
                    Long depId = Long.valueOf(department.get("id").toString());
                    V3xOrgDepartment v3xOrgDepartment = orgManager.getDepartmentById(depId);
                    //List<OrgMember> allMembers = rcDao.getAllMemberByDepId(v3xOrgDepartment.getId());
                    List<Map<String, Object>> realDeptMembers = rcDao.getRealDeptMembers(depId);
                    List<V3xOrgMember> allMembers = new ArrayList<>();
                    Set<V3xOrgMember> allMemberSet = new HashSet<>();
                    for (Map<String, Object> map : realDeptMembers){
                        long memberId = Long.parseLong(String.valueOf(map.get("id")));
                        allMemberSet.add(orgManager.getMemberById(memberId));
                        // allMembers.add(orgManager.getMemberById(memberId));
                    }
                    if (allMemberSet!=null&&!allMemberSet.isEmpty()){
                        for (V3xOrgMember orgMember : allMemberSet) {
                            int toDayState = RcUtils.personalSchedule(now.toString(), orgMember.getId(),jdbcAgent);
                            for (Integer year : yearsBetween) {
                                try {
                                    JSONObject rcJson = new JSONObject();
                                    rcJson.put("year",year);
                                    rcJson.put("userId",orgMember.getId());
                                    JSONObject memberMonthJson = rcManager.personalSchedule(rcJson);
                                    JSONObject monthDatas = memberMonthJson.getJSONObject("month_datas");
                                    JSONObject monthDetail = memberMonthJson.getJSONObject("month_detail");
                                    if (monthDatas!=null&&!monthDatas.isEmpty()){
                                        for (String key : typeMap.keySet()) {
                                            String monthVal = typeMap.get(key);
                                            JSONObject monthData = monthDatas.getJSONObject(monthVal);
                                            JSONObject monthDetailData = monthDetail.getJSONObject(monthVal);
                                            if (monthData!=null&&!monthData.isEmpty()){
                                                Integer onSite = monthData.getInteger("onSite");
                                                Integer bt = monthData.getInteger("bt");//出差
                                                Integer rl = monthData.getInteger("rl");//休假
                                                EbsRcPo ebsRcOs = new EbsRcPo();
                                                ebsRcOs.setMemberId(orgMember.getId());
                                                ebsRcOs.setName(orgMember.getName());
                                                ebsRcOs.setDepartmentId(orgMember.getOrgDepartmentId());
                                                ebsRcOs.setMonth(Integer.parseInt(key));
                                                ebsRcOs.setYear(year);
                                                ebsRcOs.setXjDays(rl);
                                                ebsRcOs.setZgDays(onSite);
                                                ebsRcOs.setCcDays(bt);
                                                ebsRcOs.setUpdateDate(new Date());
                                                EbsRcPo ebsRcPo = RcyhUtils.updateRc(ebsRcOs);
                                                JSONArray onSiteData = monthDetailData.getJSONArray("on_site_data");
                                                JSONArray homeTripData = monthDetailData.getJSONArray("homeTrip_data");
                                                JSONArray tripData = monthDetailData.getJSONArray("trip_data");
                                                JSONArray leaveData = monthDetailData.getJSONArray("leave_data");
                                                if (onSiteData!=null&&!onSiteData.isEmpty()){
                                                    RcyhUtils.rcMx(onSiteData, DqType.zg.getCode(),ebsRcPo);
                                                }
                                                if (homeTripData!=null&&!homeTripData.isEmpty()){
                                                    RcyhUtils.rcMx(homeTripData, DqType.gncc.getCode(), ebsRcPo);
                                                }
                                                if (tripData!=null&&!tripData.isEmpty()){
                                                    RcyhUtils.rcMx(tripData, DqType.gjcc.getCode(),ebsRcPo);
                                                }
                                                if (leaveData!=null&&!leaveData.isEmpty()){
                                                    RcyhUtils.rcMx(leaveData, DqType.xj.getCode(),ebsRcPo);
                                                }
                                            }
                                        }
                                        //更新年中总数据
                                        JSONObject totalData = monthDatas.getJSONObject("Total");
                                        if (totalData!=null&&!totalData.isEmpty()){
                                            Integer onSite = totalData.getInteger("onSite");
                                            Integer bt = totalData.getInteger("bt");//出差
                                            Integer rl = totalData.getInteger("rl");//休假
                                            EbsRcPo ebsRcOs = new EbsRcPo();
                                            ebsRcOs.setName(orgMember.getName());
                                            ebsRcOs.setMemberId(orgMember.getId());
                                            ebsRcOs.setDepartmentId(orgMember.getOrgDepartmentId());
                                            ebsRcOs.setMonth(0);//0代表一年总数
                                            ebsRcOs.setYear(year);
                                            ebsRcOs.setXjDays(rl);
                                            ebsRcOs.setZgDays(onSite);
                                            ebsRcOs.setCcDays(bt);
                                            ebsRcOs.setUpdateDate(new Date());
                                            EbsRcPo ebsRcPo = RcyhUtils.updateRc(ebsRcOs);
                                        }
                                    }
                                }catch (Exception e){
                                    log.error("更新人员"+ orgMember.getName()+"的"+year+"年的动迁数据异常！！！");
                                }
                            }
                        }
                    }
                    log.info("---动迁优化----动迁查询部门信息配置底表存在，开始更新RC中间表！！！");
                }
            }else{
                log.info("---动迁优化----动迁查询部门信息配置底表不存在或者配置信息为空！！！");
            }
        }catch (Exception e){
            log.error("更新RC中间表失败",e);
        }finally {
            jdbcAgent.close();
        }
        return result;
    }

    @Override
    public JSONObject handleDepartmentClick(JSONObject param){
        return null;
    }

    @Override
    public JSONObject personalSchedule(JSONObject param){
        JSONObject result = new JSONObject();
        try {
            // Map<String, String> messageLinkType = UserMessageUtil.getMessageLinkType();
            Integer year = param.getInteger("year");
            Long userId = param.getLong("userId");
            LocalDate now = LocalDate.now();
            V3xOrgMember member = orgManager.getMemberById(userId);
            // JSONObject monthDqJson = new JSONObject();
            result.put("year",year);
            result.put("userId",member.getId());
            result.put("memberId",member.getId());
            result.put("now",now.toString());
            result.put("userName",member.getName());
            List<Map<String, Object>> rcMxJson = rcyhDao.getRcMxList(result);
            if (rcMxJson!=null&&!rcMxJson.isEmpty()){
                Map<String, Object> rcMxMap = rcMxJson.get(0);
                Object state = rcMxMap.get("state");
                result.put("dayState",state);
            }
            //按月查询员工月度动迁数据
            JSONObject month_detail = new JSONObject();
            JSONObject yearCountJson = this.leadershipAgenda(result);
            if (yearCountJson!=null&&!yearCountJson.isEmpty()){
                JSONObject monthInfo = yearCountJson.getJSONObject("monthInfo");
                result.put("month_datas",monthInfo);
            }
            for (int i = 1; i <=12; i++) {
                JSONObject monthDetail = this.personalSchedule(member.getId(), year, i);
                month_detail.put(typeMap.get(String.valueOf(i)),monthDetail);
            }
            result.put("month_detail",month_detail);
        }catch (Exception e){
            log.error("获取人员排班信息失败",e);
        }
        return result;
    }


    @Override
    public JSONObject leadershipAgendaPerson(JSONObject param){
        JSONObject dataJson = new JSONObject();
        try {
            JSONArray userInfo = new JSONArray();
            LocalDate now = LocalDate.now();
            Integer year = param.getInteger("year");
            Long userId = param.getLong("userId");
            Integer state = param.getInteger("state");
            Integer page = param.getInteger("page");
            Integer limit = param.getInteger("limit");
            Long deptId = param.getLong("deptId");
            String name = param.getString("name");
            Integer sortType = param.getInteger("sortType");
            String sortMonth = param.getString("sortMonth");
            boolean ifSort = false;
            if (sortType != null && !"".equals(sortType) && sortMonth!=null && !"".equals(sortMonth)){//排序计算
                ifSort = true;
            }
            dataJson.put("userId",userId);
            dataJson.put("year",year);
            V3xOrgMember member = orgManager.getMemberById(userId);
            JSONObject jsonObject = RcUtils.personalScheduleRoles(member.getId());
            if (jsonObject != null && !jsonObject.isEmpty()) {
                Integer grade = jsonObject.getInteger("grade");
                if (grade != null && grade != 0 && grade != 3) {
                    if (grade == 1) {//总
                        FlipInfo fi = new FlipInfo(page, limit);
                        JSONObject dqMerJsonData = new JSONObject();
                        dqMerJsonData.put("month", 0);//按年度人员在岗天数排序
                        dqMerJsonData.put("year",year);
                        if (state!=null){//按状态查询
                            dqMerJsonData.put("state", state);
                            dqMerJsonData.put("dq_date", now);
                        }
                        if(deptId!=null && deptId!=0){
                            dqMerJsonData.put("deptId", deptId);
                        }
                        if (name!=null && !name.isEmpty()){
                            dqMerJsonData.put("name", name);
                        }
                        if (ifSort){
                            JSONObject pxJson = new JSONObject();
                            pxJson.put("sortType",sortType);
                            if ("Total".equals(sortMonth)){
                                pxJson.put("sortMonth",0);
                            }else{
                                for (String key:typeMap.keySet()){
                                    if (typeMap.get(key).equals(sortMonth)){
                                        pxJson.put("sortMonth",key);
                                        break;
                                    }
                                }
                            }
                            dqMerJsonData.put("pxJson", pxJson);
                        }
                        FlipInfo dqMermbers = rcyhDao.getDqMermbers(fi, dqMerJsonData);
                        List<Map<String,Object>> dqMembers= dqMermbers.getData();
                        if (dqMembers!=null&&!dqMembers.isEmpty()){
                            dataJson.put("countNum",dqMermbers.getTotal());
                            for (Map<String,Object> dqMember:dqMembers){
                                Long memberId = Long.valueOf(dqMember.get("member_id").toString());
                                V3xOrgMember dqV3xMember = orgManager.getMemberById(memberId);
                                JSONObject monthDqJson = new JSONObject();
                                monthDqJson.put("year",year);
                                monthDqJson.put("memberId",dqV3xMember.getId());
                                monthDqJson.put("now",now);
                                JSONObject memberYearData = this.leadershipAgenda(monthDqJson);
                                memberYearData.put("userName",dqV3xMember.getName());
                                userInfo.add(memberYearData);
                                log.info("查询所有动迁人员信息："+dqV3xMember.getName());
                            }
                        }
                        log.info("查询所有动迁部门信息："+dqMermbers.getData());
                    }else if(grade == 2) {//分管、主管
                        FlipInfo fi = new FlipInfo(page, limit);
                        JSONArray zgDepId = jsonObject.getJSONArray("zgDepId");
                        if (zgDepId!=null&&!zgDepId.isEmpty()){
                            JSONObject depSqlJson = new JSONObject();
                            depSqlJson.put("deptIds", zgDepId);
                            depSqlJson.put("year",year);
                            depSqlJson.put("month",now.getMonthValue());
                            if (state!=null){//按状态查询
                                depSqlJson.put("state", state);
                                depSqlJson.put("dq_date", now);
                            }
                            if(deptId!=null && deptId!=0){
                                JSONArray deptIdArray = new JSONArray();
                                deptIdArray.add(deptId);
                                depSqlJson.put("deptIds", deptIdArray);
                            }
                            if (name!=null && !name.isEmpty()){
                                depSqlJson.put("name", name);
                            }
                            if (ifSort){
                                JSONObject pxJson = new JSONObject();
                                pxJson.put("sortType",sortType);
                                if ("Total".equals(sortMonth)){
                                    pxJson.put("sortMonth",0);
                                }else{
                                    for (String key:typeMap.keySet()){
                                        if (typeMap.get(key).equals(sortMonth)){
                                            pxJson.put("sortMonth",key);
                                            break;
                                        }
                                    }
                                }
                                depSqlJson.put("pxJson", pxJson);
                            }
                            fi = rcyhDao.getDpetDqMermbers(fi, depSqlJson);
                            List<Map<String, Object>> memberLists = fi.getData();
                            if (memberLists!=null&&!memberLists.isEmpty()){
                                dataJson.put("countNum",fi.getTotal());
                                for (Map<String,Object> dqMember:memberLists){
                                    Long memberId = Long.valueOf(dqMember.get("member_id").toString());
                                    V3xOrgMember dqV3xMember = orgManager.getMemberById(memberId);
                                    JSONObject monthDqJson = new JSONObject();
                                    monthDqJson.put("year",year);
                                    monthDqJson.put("memberId",dqV3xMember.getId());
                                    monthDqJson.put("now",now);
                                    JSONObject memberYearData = this.leadershipAgenda(monthDqJson);
                                    memberYearData.put("userName",dqV3xMember.getName());
                                    userInfo.add(memberYearData);
                                    log.info("查询所有动迁人员信息："+dqV3xMember.getName());
                                }
                            }
                            log.info("查询部门动迁人员信息：");
                        }else{
                            log.info(member.getName()+" 未查询到分管，主管部门信息！！！");
                        }
                    }
                }
            }
            dataJson.put("userInfo",userInfo);
        }catch (Exception e){
            log.error("leadershipAgendaPerson异常",e);
        }
        return dataJson;
    }

    /**
    * 功能: 查询人员某年度动迁月度数据
    * @Date: 2025/4/18
    */
    public JSONObject leadershipAgenda(JSONObject param){
        JSONObject result = new JSONObject();
        try {
            result.put("year",param.getInteger("year"));
            result.put("userId",param.getLong("memberId"));
            JSONObject month_datas = new JSONObject();
            //查询当天状态
            // Date now = param.getDate("now");
            List<Map<String, Object>> rcMxJson = rcyhDao.getRcMxList(param);
            if (rcMxJson!=null&&!rcMxJson.isEmpty()){
                Map<String, Object> rcMxMap = rcMxJson.get(0);
                Object state = rcMxMap.get("state");
                result.put("state",state);
            }
            //YEAR,MEMBER_ID
            List<EbsRcPo> rcList = rcyhDao.getRcList(param);
            if (rcList!=null&&!rcList.isEmpty()){
                for (EbsRcPo rcPo:rcList){
                    JSONObject monthJson = new JSONObject();
                    Integer month = rcPo.getMonth();
                    if (month==0){
                        monthJson.put("bt",rcPo.getCcDays());
                        monthJson.put("onSite",rcPo.getZgDays());
                        monthJson.put("rl",rcPo.getXjDays());
                        month_datas.put("Total",monthJson);
                    }else{
                        String string = typeMap.get(month.toString());
                        monthJson.put("bt",rcPo.getCcDays());
                        monthJson.put("onSite",rcPo.getZgDays());
                        monthJson.put("rl",rcPo.getXjDays());
                        month_datas.put(typeMap.get(month.toString()),monthJson);
                    }
                }
            }
            result.put("monthInfo",month_datas);
            log.info("leadershipAgenda查询人员某年度动迁月度数据开始");
        }catch (Exception e){
            log.error("leadershipAgenda异常",e);
        }
        return result;
    }

    /**
    * 功能:查询员工月度数据
    * @Date: 2025/4/21
    */
    public JSONObject personalSchedule(Long userId,int year,int month){
        JSONObject result = new JSONObject();
        try {
            JSONObject rcSqlMap = new JSONObject();
            rcSqlMap.put("memberId",userId);
            rcSqlMap.put("year",year);
            rcSqlMap.put("month",month);
            List<EbsRcPo> rcList = rcyhDao.getRcList(rcSqlMap);
            if (rcList!=null&&!rcList.isEmpty()){
                EbsRcPo ebsRcPo = rcList.get(0);
                //在岗
                List<EbsRcMxPo> rcMxList2 = rcyhDao.getRcMx(ebsRcPo.getId(), 2);
                JSONArray on_site_data = new JSONArray();
                if (rcMxList2!=null && !rcMxList2.isEmpty()){
                    for (EbsRcMxPo rcMxPo:rcMxList2){
                        on_site_data.add(adf.format(rcMxPo.getDqDate()));
                    }
                }
                result.put("on_site_data",on_site_data);
                //休假
                List<EbsRcMxPo> rcMxList3 = rcyhDao.getRcMx(ebsRcPo.getId(), 3);
                JSONArray leave_data = new JSONArray();
                if (rcMxList3!=null && !rcMxList3.isEmpty()){
                    for (EbsRcMxPo rcMxPo:rcMxList3){
                        leave_data.add(adf.format(rcMxPo.getDqDate()));
                    }
                }
                result.put("leave_data",leave_data);
                //国际出差
                List<EbsRcMxPo> rcMxList1 = rcyhDao.getRcMx(ebsRcPo.getId(), 1);
                JSONArray trip_data = new JSONArray();
                if (rcMxList1!=null && !rcMxList1.isEmpty()){
                    for (EbsRcMxPo rcMxPo:rcMxList1){
                        trip_data.add(adf.format(rcMxPo.getDqDate()));
                    }
                }
                result.put("trip_data",trip_data);
                //国内出差
                List<EbsRcMxPo> rcMxList4 = rcyhDao.getRcMx(ebsRcPo.getId(), 4);
                JSONArray homeTrip_data = new JSONArray();
                if (rcMxList4!=null && !rcMxList4.isEmpty()){
                    for (EbsRcMxPo rcMxPo:rcMxList4){
                        homeTrip_data.add(adf.format(rcMxPo.getDqDate()));
                    }
                }
                result.put("homeTrip_data",homeTrip_data);
                JSONArray all_data = new JSONArray();
                result.put("all_data",all_data);
                log.info("personalSchedule查询员工月度数据：");

            }else{
                log.info("动迁档案不存在！！！");
            }
            log.info("personalSchedule查询员工月度数据开始");
        }catch (Exception e){
            log.error("personalSchedule异常",e);
        }
        return result;
    }

}
